package com.pony.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pony.dto.GoodsDTO;
import com.pony.dto.PageDTO;
import com.pony.dto.TypeDTO;
import com.pony.entity.Goods;
import com.pony.entity.Type;
import com.pony.enums.AppHttpCodeEnum;
import com.pony.mapper.GoodsMapper;
import com.pony.mapper.TypeMapper;
import com.pony.result.R;
import com.pony.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pony.utils.BeanUtils;
import com.pony.utils.CollUtils;
import com.pony.utils.StringUtils;
import com.pony.utils.TXCloudFileUtils;
import com.pony.vo.GoodsVO;
import com.pony.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pony
 * @since 2023-11-16
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {
    //腾讯云对象存储 路径-访问域名
    private static String url = "https://pony-1312090731.cos.ap-beijing.myqcloud.com/";
    // 头像存储的文件夹
    private static String imgPath = "yxy/images/";

    @Autowired
    private TypeMapper typeMapper;

    /**
     * 上传酒水图片
     * @param file 图片
     * @return
     */
    @Override
    public R uploadImg(MultipartFile file) {
        //1、上传文件 返回值是 key，即图片重新命名的名字
        String imgName = TXCloudFileUtils.upLoad(imgPath, file);
        //2、拼接 img 访问路径，并写入数据库
        String imgUrl = url  + imgPath + imgName;
        //3、将结果返回给前端
        return R.success().message("酒水图片上传成功").data("singerImgUrl", imgUrl);
    }

    /**
     * 添加酒水
     * @param goodsDto
     * @return
     */
    @Override
    public R add(GoodsDTO goodsDto) {
        // 1、属性拷贝
        Goods goods = BeanUtils.copyBean(goodsDto, Goods.class);
        // 2、添加前判断分类名称是否有重复
        List<Goods> listDB = lambdaQuery()
                .eq(Goods::getName, goods.getName())
                .list();
        if (CollUtils.isNotEmpty(listDB)&&listDB.size()>=1){
            return R.error(AppHttpCodeEnum.DATA_REPEAT);
        }
        // 3、保存
        save(goods);
        return R.success().message("酒水添加成功");
    }

    /**
     * 酒水分页
     * @param pageDTO
     * @return
     */
    @Override
    public R getPage(PageDTO pageDTO) {
        // 1、查询分页数据
        Page<Goods> page = new Page<>(pageDTO.getCurrent(), pageDTO.getSize());
        Page<Goods> goodsPage = lambdaQuery()
                .like(!StringUtils.isBlank(pageDTO.getKeyword()), Goods::getName, pageDTO.getKeyword())
                .orderByAsc(Goods::getOrderId)
                .page(page);
        // 2、封装vo
        List<GoodsVO> voList = BeanUtils.copyList(goodsPage.getRecords(), GoodsVO.class);
        // 查询出所有 TypeId
        List<Long> typeIdList = goodsPage.getRecords().stream()
                .map(goods -> goods.getTypeId())
                .collect(Collectors.toList());
        // 根据 typeId 查询所有 typeId
        List<Type> typeList = typeMapper.selectBatchIds(typeIdList);
        // 收集成一个map key：id，value：name
        Map<Long, String> typeMap = typeList.stream().collect(Collectors.toMap(Type::getId, Type::getName));
        // 遍历voList封装typeName
        voList.forEach(goodsVO -> goodsVO.setTypeName(typeMap.get(goodsVO.getTypeId())));

        PageVO<GoodsVO> pageVO = new PageVO<>();
        pageVO.setCurrent(pageDTO.getCurrent());
        pageVO.setSize(pageDTO.getSize());
        pageVO.setTotal(goodsPage.getTotal());
        pageVO.setRecords(voList);
        //3、返回数据
        return R.success().message("酒水分页信息").data("singerPage", pageVO);
    }

    /**
     * 更改酒水状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public void setStatus(Integer id, Integer status) {
        lambdaUpdate()
                .eq(Goods::getId, id)
                .set(Goods::getStatus, status)
                .update();
    }

    /**
     * 根据分类id，查询单个信息
     * @param id
     * @return
     */
    @Override
    public R selectOneById(Integer id) {
        Goods goods = getById(id);
        return R.success().message("根据id，查询单个酒水数据").data("singer", goods);
    }

    /**
     * 修改数据
     * @param goodsDTO
     * @return
     */
    @Override
    public R updateSinger(GoodsDTO goodsDTO) {
        // 1、修改前判断酒水名称是否有重复
        List<Goods> listDB = lambdaQuery()
                .eq(StringUtils.isNotBlank(goodsDTO.getName()), Goods::getName, goodsDTO.getName())
                .list();
        // 自己是一定会被查出来的，自己不算，所以是 >= 2
        if (listDB.size()>=2){
            return R.error(AppHttpCodeEnum.DATA_REPEAT);
        }
        // 2、修改
        lambdaUpdate()
                .eq(Goods::getId, goodsDTO.getId())
                .set(StringUtils.isNotBlank(goodsDTO.getName()), Goods::getName, goodsDTO.getName())
                .set(StringUtils.isNotBlank(goodsDTO.getRemarks()), Goods::getRemarks, goodsDTO.getRemarks())
                .set(StringUtils.isNotBlank(goodsDTO.getImage()), Goods::getImage, goodsDTO.getImage())
                .set(goodsDTO.getTypeId()!=null, Goods::getTypeId, goodsDTO.getTypeId())
                .update();
        return R.success().message("修改成功");
    }

    @Override
    public R updateType(GoodsDTO goodsDTO) {
        //修改
        lambdaUpdate()
                .eq(Goods::getId, goodsDTO.getId())
                .set(StringUtils.isNotBlank(goodsDTO.getName()), Goods::getName, goodsDTO.getName())
                .set(StringUtils.isNotBlank(goodsDTO.getRemarks()), Goods::getRemarks, goodsDTO.getRemarks())
                .set(StringUtils.isNotBlank(goodsDTO.getImage()), Goods::getImage, goodsDTO.getImage())
                .set(goodsDTO.getTypeId()!=null, Goods::getTypeId, goodsDTO.getTypeId())
                .update();
        return R.success().message("修改成功");
    }

    /**
     * 根据id删除酒水
     * @param id
     * @return
     */
    @Override
    public R deleteOneById(Integer id) {
        // 删除
        removeById(id);
        return R.success().message("删除成功");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public R deleteBatch(List<Integer> ids) {
        // 删除
        removeByIds(ids);
        return R.success().message("批量删除成功");
    }
}
